'use client'

import * as z from 'zod'
import Link from 'next/link'
import { useForm } from "react-hook-form"
import { useState, useTransition } from 'react'
import { useSearchParams } from 'next/navigation'
import { zodResolver } from "@hookform/resolvers/zod"

import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import FormError from '@/components/form-error'
import FormSuccess from '@/components/form-success'
import CardWrapper from "@/components/auth/card-wrapper"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage
} from '@/components/ui/form'

import { login } from '@/actions/login'
import { LoginSchema } from '@/schemas/auth'

const LoginForm = () => {
    const searchParams = useSearchParams()
    const callbackUrl = searchParams.get('callbackUrl')
    const urlError: string = searchParams.get('error') === 'OAuthAccountNotLinked'
        ? 'Email already in use with different provider!'
        : ''

    const [isPending, startTransition] = useTransition()
    const [error, setError] = useState<string | undefined>('')
    const [success, setSuccess] = useState<string | undefined>('')
    const [showTwoFactor, setShowTwoFactor] = useState<boolean>(false)

    const form = useForm<z.infer<typeof LoginSchema>>({
        resolver: zodResolver(LoginSchema),
        defaultValues: {
            email: '',
            password: ''
        }
    })

    const handleSubmit = (values: z.infer<typeof LoginSchema>) => {
        setError('')
        setSuccess('')
        startTransition(() => {
            login(values, callbackUrl).then(data => {
                if (data?.error) {
                    form.reset()
                    setError(data.error)
                }

                if (data?.success) {
                    form.reset()
                    setSuccess(data.success)
                }

                if (data?.twoFactor) {
                    setShowTwoFactor(true)
                }
            })
        })
    }

    return (
        <CardWrapper
            headerLabel="- 欢迎回来 -"
            backButtonLabel="还没有账号?"
            backButtonPath="/auth/register"
            showSocial
        >
            <Form {...form}>
                <form
                    onSubmit={form.handleSubmit(handleSubmit)}
                    className='space-y-6'
                >
                    <div className='space-y-4'>
                        {showTwoFactor && (
                            <FormField
                                control={form.control}
                                name='code'
                                render={(({ field, fieldState }) => (
                                    <FormItem>
                                        <FormLabel htmlFor='code'>Two Factor Code</FormLabel>
                                        <FormControl>
                                            <Input {...field} disabled={isPending} placeholder='123456' />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                ))}
                            />
                        )}
                        {!showTwoFactor && (
                            <>
                                <FormField
                                    control={form.control}
                                    name='email'
                                    render={(({ field, fieldState }) => (
                                        <FormItem>
                                            <FormLabel htmlFor='email'>邮箱</FormLabel>
                                            <FormControl>
                                                <Input {...field} disabled={isPending} placeholder='name@example.com' type='email' />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    ))}
                                />
                                <FormField
                                    control={form.control}
                                    name='password'
                                    render={(({ field, fieldState }) => (
                                        <FormItem>
                                            <FormLabel htmlFor='passowrd'>密码</FormLabel>
                                            <FormControl>
                                                <Input {...field} disabled={isPending} placeholder='******' type='password' />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    ))}
                                />
                                <Button
                                    size='sm'
                                    variant='link'
                                    asChild
                                    className='px-0 font-normal'
                                >
                                    <Link href='/auth/reset'>
                                        忘记密码?
                                    </Link>
                                </Button>
                            </>
                        )}
                    </div>
                    <FormError message={error || urlError} />
                    <FormSuccess message={success} />
                    <Button
                        disabled={isPending}
                        type='submit'
                        className='w-full'
                    >
                        {showTwoFactor ? '确 认' : '登 录'}
                    </Button>
                </form>
            </Form>
        </CardWrapper >
    )
}

export default LoginForm